<template>
  <el-form size="small">
  <el-form-item>
    <el-radio v-model='radioValue' :label="1">
    秒，允许的通配符[, - * /]
    </el-radio>
  </el-form-item>
  <el-form-item>
    <el-radio v-model='radioValue' :label="2">
    周期从
    <el-input-number v-model='cycle01' :min="0" :max="58" /> -
    <el-input-number v-model='cycle02' :min="cycle01 ? cycle01 + 1 : 1" :max="59" /> 秒
    </el-radio>
  </el-form-item>
  <el-form-item>
    <el-radio v-model='radioValue' :label="3">
    从
    <el-input-number v-model='average01' :min="0" :max="58" /> 秒开始，每
    <el-input-number v-model='average02' :min="1" :max="59 - average01 || 0" /> 秒执行一次
    </el-radio>
  </el-form-item>
  <el-form-item>
    <el-radio v-model='radioValue' :label="4">
    指定
    <el-select clearable v-model="checkboxList" placeholder="可多选" multiple style="width:100%">
      <el-option v-for="item in 60" :key="item" :value="item-1">{{item-1}}</el-option>
    </el-select>
    </el-radio>
  </el-form-item>
  </el-form>
</template>

<script>
import { ref, watch } from 'vue';

export default {
  name: 'crontab-second',
  props: ['check', 'radioParent'],
  setup(props) {
  const radioValue = ref(1);
  const cycle01 = ref(1);
  const cycle02 = ref(2);
  const average01 = ref(0);
  const average02 = ref(1);
  const checkboxList = ref([]);
  const checkNum = (num, min, max) => {
    return Math.max(min, Math.min(num, max));
  };

  watch(radioValue, () => {
    switch (radioValue.value) {
    case 1:
      emitUpdate('second', '*', 'second');
      break;
    case 2:
      emitUpdate('second', cycleTotal.value);
      break;
    case 3:
      emitUpdate('second', averageTotal.value);
      break;
    case 4:
      emitUpdate('second', checkboxString.value);
      break;
    }
  });

  watch([cycle01, cycle02], () => {
    if (radioValue.value === '2') {
    emitUpdate('second', cycleTotal.value);
    }
  });

  watch([average01, average02], () => {
    if (radioValue.value === '3') {
    emitUpdate('second', averageTotal.value);
    }
  });

  watch(checkboxList, () => {
    if (radioValue.value === '4') {
    emitUpdate('second', checkboxString.value);
    }
  });

  const emitUpdate = (arg1, arg2, arg3) => {
    if (props.check) {
    props.check(arg1, arg2, arg3);
    }
  };

  const cycleTotal = computed(() => {
    const cycle01Value = checkNum(cycle01.value, 0, 58);
    const cycle02Value = checkNum(cycle02.value, cycle01Value ? cycle01Value + 1 : 1, 59);
    return `${cycle01Value}-${cycle02Value}`;
  });

  const averageTotal = computed(() => {
    const average01Value = checkNum(average01.value, 0, 58);
    const average02Value = checkNum(average02.value, 1, 59 - average01Value || 0);
    return `${average01Value}/${average02Value}`;
  });

  const checkboxString = computed(() => {
    const str = checkboxList.value.join();
    return str === '' ? '*' : str;
  });

  return { radioValue, cycle01, cycle02, average01, average02, checkboxList };
  },
};
</script>
